﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Smile.Mvvm.ViewModel;

namespace Smile.Mvvm.Command
{
    public class SmileCommand : ISmileCommand
    {
        // @Events
        public event EventHandler CanExecuteChanged;


        // @public
        public SmileCommand(Action<object> actionToExecute, Predicate<object> canExecute = null)
        {
            // Execute action
            if (actionToExecute == null)
            {
                throw new ArgumentNullException("SmileCommand: You must provide an action to execute.");
            }
            _executeAction = actionToExecute;

            // CanExecute predicat
            if (canExecute == null)
            {
                _canExecutePredicat = new Predicate<object>((param) => true);
            }
            else
            {
                _canExecutePredicat = canExecute;
            }
        }

        public bool CanExecute(object parameter = null)
        {
            if (_canExecutePredicat == null)
            {
                return true;
            }

            return _canExecutePredicat(parameter);
        }

        public void Execute(object parameter = null)
        {
            _executeAction(parameter);
        }

        public void RefreshCanExecuteChanged(object parameter = null)
        {
            if (CanExecute() == _lastCanExecuteState)
            {
                _lastCanExecuteState = CanExecute();
                RaiseCanExecuteChanged();
            }
        }


        // @Protected
        protected readonly Action<object>       _executeAction;
        protected readonly Predicate<object>    _canExecutePredicat;
        protected bool                          _lastCanExecuteState = true;


        protected void RaiseCanExecuteChanged()
        {
            if (CanExecuteChanged != null)
            {
                CanExecuteChanged(this, EventArgs.Empty);
            }
        }
    }
}
